<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.json',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="Channel使用规范在不能更改channel状态的情况下，没有简单普遍的方式来检查channel是否已经关闭了 关闭已经关闭的channel会导致panic，所以在closer(关闭者)不知道channel是否已经关闭的情况下去关闭channel是很危险的 发送值到已经关闭的channel会导致panic，所以如果sender(发送者)在不知道channel是否已经关闭的情况下去向channel">
<meta name="keywords" content="golang">
<meta property="og:type" content="article">
<meta property="og:title" content="golang优雅的关闭channel">
<meta property="og:url" content="https://unix2dos.github.io/p/8b210700.html">
<meta property="og:site_name" content="Levon&#39;s Blog">
<meta property="og:description" content="Channel使用规范在不能更改channel状态的情况下，没有简单普遍的方式来检查channel是否已经关闭了 关闭已经关闭的channel会导致panic，所以在closer(关闭者)不知道channel是否已经关闭的情况下去关闭channel是很危险的 发送值到已经关闭的channel会导致panic，所以如果sender(发送者)在不知道channel是否已经关闭的情况下去向channel">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-09-27T15:36:51.099Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="golang优雅的关闭channel">
<meta name="twitter:description" content="Channel使用规范在不能更改channel状态的情况下，没有简单普遍的方式来检查channel是否已经关闭了 关闭已经关闭的channel会导致panic，所以在closer(关闭者)不知道channel是否已经关闭的情况下去关闭channel是很危险的 发送值到已经关闭的channel会导致panic，所以如果sender(发送者)在不知道channel是否已经关闭的情况下去向channel">
  <link rel="canonical" href="https://unix2dos.github.io/p/8b210700">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>golang优雅的关闭channel | Levon's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Levon's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">微信:  L6241425</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>时光</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://unix2dos.github.io/p/8b210700.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Levon">
      <meta itemprop="description" content="Never Give Up">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Levon's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">golang优雅的关闭channel

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2018-05-27 23:31:19" itemprop="dateCreated datePublished" datetime="2018-05-27T23:31:19+08:00">2018-05-27</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-27 23:36:51" itemprop="dateModified" datetime="2019-09-27T23:36:51+08:00">2019-09-27</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/" itemprop="url" rel="index"><span itemprop="name">1-编程语言</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/golang/" itemprop="url" rel="index"><span itemprop="name">golang</span></a></span>

                
                
              
            </span>
          

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Disqus：</span>
    
    <a title="disqus" href="/p/8b210700.html#comments" itemprop="discussionUrl"><span class="post-comments-count disqus-comment-count" data-disqus-identifier="p/8b210700.html" itemprop="commentCount"></span></a>
  </span>
  
  
          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              
                <span class="post-meta-item-text">本文字数：</span>
              
              <span>7.1k</span>
            </span>
          
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              
              <span>6 分钟</span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="Channel使用规范"><a href="#Channel使用规范" class="headerlink" title="Channel使用规范"></a>Channel使用规范</h3><p>在不能更改channel状态的情况下，没有简单普遍的方式来检查channel是否已经关闭了</p>
<p>关闭已经关闭的channel会导致panic，所以在closer(关闭者)不知道channel是否已经关闭的情况下去关闭channel是很危险的</p>
<p>发送值到已经关闭的channel会导致panic，所以如果sender(发送者)在不知道channel是否已经关闭的情况下去向channel发送值是很危险的</p>
<h3 id="The-Channel-Closing-Principle"><a href="#The-Channel-Closing-Principle" class="headerlink" title="The Channel Closing Principle"></a>The Channel Closing Principle</h3><p>在使用Go channel的时候，一个适用的原则是<em>不要从接收端关闭channel，也不要关闭有多个并发发送者的channel</em>。</p>
<p>换句话说，如果sender(发送者)只是唯一的sender或者是channel最后一个活跃的sender，那么你应该在sender的goroutine关闭channel，从而通知receiver(s)(接收者们)已经没有值可以读了。维持这条原则将保证永远不会发生向一个已经关闭的channel发送值或者关闭一个已经关闭的channel。</p>
<a id="more"></a>

<h3 id="打破Channel-Closing-Principle的解决方案"><a href="#打破Channel-Closing-Principle的解决方案" class="headerlink" title="打破Channel Closing Principle的解决方案"></a>打破Channel Closing Principle的解决方案</h3><p>如果你因为某种原因从接收端（receiver side）关闭channel或者在多个发送者中的一个关闭channel，那么你应该使用列在<a href="https://link.jianshu.com/?t=http://www.tapirgames.com/blog/golang-panic-use-cases" target="_blank" rel="noopener">Golang panic/recover Use Cases</a>的函数来安全地发送值到channel中（假设channel的元素类型是T）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">func SafeSend(ch chan T, value T) (closed bool) &#123;</span><br><span class="line">    defer func() &#123;</span><br><span class="line">        if recover() != nil &#123;</span><br><span class="line">            // the return result can be altered </span><br><span class="line">            // in a defer function call</span><br><span class="line">            closed = true</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;()</span><br><span class="line">    </span><br><span class="line">    ch &lt;- value // panic if ch is closed</span><br><span class="line">    return false // &lt;=&gt; closed = false; return</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>同样的想法也可以用在从多个goroutine关闭channel中：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">func SafeClose(ch chan T) (justClosed bool) &#123;</span><br><span class="line">	defer func() &#123;</span><br><span class="line">		if recover() != nil &#123;</span><br><span class="line">			justClosed = false</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;()</span><br><span class="line">	</span><br><span class="line">	// assume ch != nil here.</span><br><span class="line">	close(ch) // panic if ch is closed</span><br><span class="line">	return true // &lt;=&gt; justClosed = true; return</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>很多人喜欢用<code>sync.Once</code>来关闭channel：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"> type MyChannel struct &#123;</span><br><span class="line">	C    chan T</span><br><span class="line">	once sync.Once</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func NewMyChannel() *MyChannel &#123;</span><br><span class="line">	return &amp;MyChannel&#123;C: make(chan T)&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func (mc *MyChannel) SafeClose() &#123;</span><br><span class="line">	mc.once.Do(func() &#123;</span><br><span class="line">		close(mc.C)</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>要知道golang的设计者不提供SafeClose或者SafeSend方法是有原因的，他们本来就不推荐在消费端或者在并发的多个生产端关闭channel，比如关闭只读channel在语法上就彻底被禁止使用了。</p>
<h3 id="优雅的关闭Channel的方法"><a href="#优雅的关闭Channel的方法" class="headerlink" title="优雅的关闭Channel的方法"></a>优雅的关闭Channel的方法</h3><p>上文的SafeSend方法一个很大的劣势在于它不能用在select块的case语句中。而另一个很重要的劣势在于像我这样对代码有洁癖的人来说，使用panic/recover和sync/mutex来搞定不是那么的优雅。下面我们引入在不同的场景下可以使用的纯粹的优雅的解决方法。</p>
<h4 id="多个消费者，单个生产者。"><a href="#多个消费者，单个生产者。" class="headerlink" title="多个消费者，单个生产者。"></a>多个消费者，单个生产者。</h4><p>这种情况最简单，直接让生产者关闭channel好了。 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">	&quot;time&quot;</span><br><span class="line">	&quot;math/rand&quot;</span><br><span class="line">	&quot;sync&quot;</span><br><span class="line">	&quot;log&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">	rand.Seed(time.Now().UnixNano())</span><br><span class="line">	log.SetFlags(0)</span><br><span class="line">	</span><br><span class="line"></span><br><span class="line">	const MaxRandomNumber = 100000</span><br><span class="line">	const NumReceivers = 100</span><br><span class="line">	</span><br><span class="line">	wgReceivers := sync.WaitGroup&#123;&#125;</span><br><span class="line">	wgReceivers.Add(NumReceivers)</span><br><span class="line">	</span><br><span class="line"></span><br><span class="line">	dataCh := make(chan int, 100)</span><br><span class="line">	</span><br><span class="line">	// 一个生产者</span><br><span class="line">	go func() &#123;</span><br><span class="line">		for &#123;</span><br><span class="line">			if value := rand.Intn(MaxRandomNumber); value == 0 &#123;</span><br><span class="line">				close(dataCh)</span><br><span class="line">				return</span><br><span class="line">			&#125; else &#123;			</span><br><span class="line">				dataCh &lt;- value</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;()</span><br><span class="line">	</span><br><span class="line">	// 多个消费者</span><br><span class="line">	for i := 0; i &lt; NumReceivers; i++ &#123;</span><br><span class="line">		go func() &#123;</span><br><span class="line">			defer wgReceivers.Done()</span><br><span class="line">			</span><br><span class="line">			for value := range dataCh &#123;</span><br><span class="line">				log.Println(value)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;()</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	wgReceivers.Wait()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="多个生产者，单个消费者。"><a href="#多个生产者，单个消费者。" class="headerlink" title="多个生产者，单个消费者。"></a>多个生产者，单个消费者。</h4><p>这种情况要比上面的复杂一点。我们不能在消费端关闭channel，因为这违背了channel关闭原则。但是我们可以让消费端关闭一个附加的信号来通知发送端停止生产数据。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">	&quot;time&quot;</span><br><span class="line">	&quot;math/rand&quot;</span><br><span class="line">	&quot;sync&quot;</span><br><span class="line">	&quot;log&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">	rand.Seed(time.Now().UnixNano())</span><br><span class="line">	log.SetFlags(0)</span><br><span class="line">	</span><br><span class="line"></span><br><span class="line">	const MaxRandomNumber = 100000</span><br><span class="line">	const NumSenders = 1000</span><br><span class="line">	</span><br><span class="line">	wgReceivers := sync.WaitGroup&#123;&#125;</span><br><span class="line">	wgReceivers.Add(1)</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	dataCh := make(chan int, 100)</span><br><span class="line">	stopCh := make(chan struct&#123;&#125;)</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	// 多个生产者</span><br><span class="line">	for i := 0; i &lt; NumSenders; i++ &#123;</span><br><span class="line">		go func() &#123;</span><br><span class="line">			for &#123;</span><br><span class="line">		</span><br><span class="line">				// 目的是尝试退出, 因为越早越好, 此处可以省略, 因为就算多发送了值, 消费者也不会理会了</span><br><span class="line">				select &#123;</span><br><span class="line">				case &lt;- stopCh:</span><br><span class="line">					return</span><br><span class="line">				default:</span><br><span class="line">				&#125;</span><br><span class="line">			</span><br><span class="line"></span><br><span class="line">				select &#123;</span><br><span class="line">				case &lt;- stopCh:</span><br><span class="line">					return</span><br><span class="line">				case dataCh &lt;- rand.Intn(MaxRandomNumber):</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;()</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	// 一个消费者</span><br><span class="line">	go func() &#123;</span><br><span class="line">		defer wgReceivers.Done()</span><br><span class="line">		</span><br><span class="line">		for value := range dataCh &#123;</span><br><span class="line">			if value == MaxRandomNumber-1 &#123;</span><br><span class="line">				</span><br><span class="line">				// 这里即是dataCh 的消费者, 也是 stopCh 的生产者</span><br><span class="line">				close(stopCh)</span><br><span class="line">				return</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			log.Println(value)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;()</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	wgReceivers.Wait()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>就上面这个例子，生产者同时也是退出信号channel的接受者，退出信号channel仍然是由它的生产端关闭的，所以这仍然没有违背<strong>channel关闭原则</strong>。值得注意的是，这个例子中生产端和接受端都没有关闭消息数据的channel，channel在没有任何goroutine引用的时候会自行关闭，而不需要显示进行关闭。</p>
<h4 id="多个生产者，多个消费者"><a href="#多个生产者，多个消费者" class="headerlink" title="多个生产者，多个消费者"></a>多个生产者，多个消费者</h4><p>这是最复杂的一种情况，我们既不能让接受端也不能让发送端关闭channel。我们甚至都不能让接受者关闭一个退出信号来通知生产者停止生产。因为我们不能违反<strong>channel关闭原则</strong>。但是我们可以引入一个额外的协调者来关闭附加的退出信号channel。  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">	&quot;time&quot;</span><br><span class="line">	&quot;math/rand&quot;</span><br><span class="line">	&quot;sync&quot;</span><br><span class="line">	&quot;log&quot;</span><br><span class="line">	&quot;strconv&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">	rand.Seed(time.Now().UnixNano())</span><br><span class="line">	log.SetFlags(0)</span><br><span class="line">	</span><br><span class="line"></span><br><span class="line">	const MaxRandomNumber = 100000</span><br><span class="line">	const NumReceivers = 10</span><br><span class="line">	const NumSenders = 1000</span><br><span class="line">	</span><br><span class="line">	wgReceivers := sync.WaitGroup&#123;&#125;</span><br><span class="line">	wgReceivers.Add(NumReceivers)</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	dataCh := make(chan int, 100)</span><br><span class="line">	stopCh := make(chan struct&#123;&#125;) //生产者是主持人, 消费者是 (dataCh所有生产者和消费者)</span><br><span class="line">	</span><br><span class="line">	toStop := make(chan string, 1) //作用是通知主持人去关闭stopCh, 生产者是 (dataCh所有生产者和消费者) 消费者是主持人</span><br><span class="line">		</span><br><span class="line">	</span><br><span class="line">	var stoppedBy string</span><br><span class="line">	</span><br><span class="line">	// 主持人</span><br><span class="line">	go func() &#123;</span><br><span class="line">		stoppedBy = &lt;- toStop</span><br><span class="line">		close(stopCh)</span><br><span class="line">	&#125;()</span><br><span class="line">	</span><br><span class="line">	// 多个生产者</span><br><span class="line">	for i := 0; i &lt; NumSenders; i++ &#123;</span><br><span class="line">		go func(id string) &#123;</span><br><span class="line">			for &#123;</span><br><span class="line">				value := rand.Intn(MaxRandomNumber)</span><br><span class="line">				if value == 0 &#123;</span><br><span class="line">					//通知主持人去干关闭的活</span><br><span class="line">					select &#123;</span><br><span class="line">					case toStop &lt;- &quot;sender#&quot; + id:</span><br><span class="line">					default:</span><br><span class="line">					&#125;</span><br><span class="line">					return</span><br><span class="line">				&#125;</span><br><span class="line">				</span><br><span class="line">			</span><br><span class="line">                //尝试尽早退出, 这里不能省略, 因为可能会导致多发送一次</span><br><span class="line">				select &#123;</span><br><span class="line">				case &lt;- stopCh:</span><br><span class="line">					return</span><br><span class="line">				default:</span><br><span class="line">				&#125;</span><br><span class="line">				</span><br><span class="line"></span><br><span class="line">				select &#123;</span><br><span class="line">				case &lt;- stopCh:</span><br><span class="line">					return</span><br><span class="line">				case dataCh &lt;- value:</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;(strconv.Itoa(i))</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	// 多个消费者</span><br><span class="line">	for i := 0; i &lt; NumReceivers; i++ &#123;</span><br><span class="line">		go func(id string) &#123;</span><br><span class="line">			defer wgReceivers.Done()</span><br><span class="line">			</span><br><span class="line">			for &#123;</span><br><span class="line">				//尝试尽早退出, 这里不能省略, 因为可能会导致多接收一次</span><br><span class="line">				select &#123;</span><br><span class="line">				case &lt;- stopCh:</span><br><span class="line">					return</span><br><span class="line">				default:</span><br><span class="line">				&#125;</span><br><span class="line">				</span><br><span class="line">			</span><br><span class="line">				//注意此处如果 stopCh 关闭了, 下面也有能 return 不了</span><br><span class="line">                //因为dataCh也有可能select 到, 所以上一个 select语句不能省略</span><br><span class="line">                </span><br><span class="line">                </span><br><span class="line">				select &#123;</span><br><span class="line">				case &lt;- stopCh:</span><br><span class="line">					return</span><br><span class="line">				case value := &lt;-dataCh:</span><br><span class="line">					if value == MaxRandomNumber-1 &#123;</span><br><span class="line">						//通知主持人去干关闭的活</span><br><span class="line">						select &#123;</span><br><span class="line">						case toStop &lt;- &quot;receiver#&quot; + id:</span><br><span class="line">						default:</span><br><span class="line">						&#125;</span><br><span class="line">						return</span><br><span class="line">					&#125;</span><br><span class="line">					</span><br><span class="line">					log.Println(value)</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;(strconv.Itoa(i))</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line">	wgReceivers.Wait()</span><br><span class="line">	log.Println(&quot;stopped by&quot;, stoppedBy)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这个例子中，仍然遵守着<em>channel closing principle</em>。 请注意channel <code>toStop</code>的缓冲大小是1.这是为了避免当mederator goroutine 准备好之前第一个通知就已经发送了，导致丢失。</p>
<h4 id="结论"><a href="#结论" class="headerlink" title="结论"></a><strong>结论</strong></h4><p>没有任何场景值得你去打破channel关闭原则，如果你遇到这样的一种特殊场景，还是建议你好好思考一下自己设计，是不是该重构一下了。</p>
<h4 id="个人疑问解答"><a href="#个人疑问解答" class="headerlink" title="个人疑问解答"></a><a href="https://www.jianshu.com/p/d24dfbb33781" target="_blank" rel="noopener">个人疑问解答</a></h4><p>楼主你好, 关于第三个例子有些问题请教</p>
<ol>
<li>value==0时, 为什么还要加个select, 不能直接发送给toStop吗?</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">if value == 0 &#123;</span><br><span class="line">select &#123;</span><br><span class="line">case toStop &lt;- &quot;sender#&quot; + id:</span><br><span class="line">default:</span><br><span class="line">&#125;</span><br><span class="line">return</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>因为可能多个生产者或者多个消费者满足条件, 防止阻塞</p>
</blockquote>
<ol start="2">
<li>select stopCh 为什么写了两次? 第一个select可以省略吗?</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">select &#123;</span><br><span class="line">case &lt;- stopCh:</span><br><span class="line">	return</span><br><span class="line">default:</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">select &#123;</span><br><span class="line">case &lt;- stopCh:</span><br><span class="line">	return</span><br><span class="line">case dataCh &lt;- value:</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>为了尽早退出, 因为第二个 Select有可能 select 到dataCh, 虽然已经通知关闭了</p>
</blockquote>
<ol start="3">
<li><p>toStop的缓冲大小是1, 为了避免准备好之前通知就发送了怎么理解??</p>
<p>请注意channel toStop的缓冲大小是1.这是为了避免当mederator goroutine 准备好之前第一个通知就已经发送了，导致丢失。</p>
</li>
</ol>
<blockquote>
<p>因为有缓冲的 发送 happens_before 接收之前, 所以mederator能保证接收到数据</p>
<p>无缓冲的 接收 happens_before 发送之间,  可能会丢失数据</p>
</blockquote>

    </div>

    
    
    
        
      
        <div id="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作, 一个耿直的笑脸~</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Levon 微信支付">
        <p>微信支付</p>
      </div>
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="Levon 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/golang/" rel="tag"># golang</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/p/6196d525.html" rel="next" title="golang内存模型和happens_before">
                  <i class="fa fa-chevron-left"></i> golang内存模型和happens_before
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/p/aca47db0.html" rel="prev" title="golang优雅的等待或通知goroutine退出">
                  golang优雅的等待或通知goroutine退出 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    
  <div class="comments" id="comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
    </div>
  </div>
  
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Channel使用规范"><span class="nav-number">1.</span> <span class="nav-text">Channel使用规范</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#The-Channel-Closing-Principle"><span class="nav-number">2.</span> <span class="nav-text">The Channel Closing Principle</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#打破Channel-Closing-Principle的解决方案"><span class="nav-number">3.</span> <span class="nav-text">打破Channel Closing Principle的解决方案</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优雅的关闭Channel的方法"><span class="nav-number">4.</span> <span class="nav-text">优雅的关闭Channel的方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#多个消费者，单个生产者。"><span class="nav-number">4.1.</span> <span class="nav-text">多个消费者，单个生产者。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多个生产者，单个消费者。"><span class="nav-number">4.2.</span> <span class="nav-text">多个生产者，单个消费者。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多个生产者，多个消费者"><span class="nav-number">4.3.</span> <span class="nav-text">多个生产者，多个消费者</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#结论"><span class="nav-number">4.4.</span> <span class="nav-text">结论</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#个人疑问解答"><span class="nav-number">4.5.</span> <span class="nav-text">个人疑问解答</span></a></li></ol></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Levon">
  <p class="site-author-name" itemprop="name">Levon</p>
  <div class="site-description" itemprop="description">Never Give Up</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">76</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/unix2dos" title="GitHub &rarr; https://github.com/unix2dos" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:levonfly@gmail.com" title="E-Mail &rarr; mailto:levonfly@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://twitter.com/levonfly" title="Twitter &rarr; https://twitter.com/levonfly" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://weibo.com/l6241425" title="Weibo &rarr; https://weibo.com/l6241425" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Levon</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">507k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:41</span>
</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  <script src="/js/local-search.js?v=7.4.0"></script>














  

  

  

<script>
  function loadCount() {
    var d = document, s = d.createElement('script');
    s.src = 'https://levonfly.disqus.com/count.js';
    s.id = 'dsq-count-scr';
    (d.head || d.body).appendChild(s);
  }
  // defer loading until the whole page loading is completed
  window.addEventListener('load', loadCount, false);
</script>
<script>
  function disqus_config() {
    this.page.url = "https://unix2dos.github.io/p/8b210700.html";
    this.page.identifier = "p/8b210700.html";
    this.page.title = 'golang优雅的关闭channel';};
  function loadComments() {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://levonfly.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  }
    window.addEventListener('load', loadComments, false);
  
</script>

</body>
</html>
